<?php

namespace App\Models\Api;

use App\Tools\Financial;
use App\Tools\Prstatic;
use Illuminate\Database\Eloquent\Model;
use App\Models\Api\Goods;
use Illuminate\Support\Facades\Redis;

class StoreOrder extends Model
{

    protected $table = 'store_order';
    protected $primaryKey = 'id';
    protected $dateFormat = 'U'; // 时间戳
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s'
    ];

    /**
     * 获取列表
     * @param $where
     * @param int $limit
     * @return mixed
     */
    public static function getPageList($store_id, $type = 1, $limit = 15)
    {
        $db = self::where(['store_id' => $store_id])
            ->select(['id', 'order_sn', 'total_number', 'order_amount', 'order_status', 'send_status', 'created_at']);
        switch ($type) {
            case 1:
                break;
            case 2:
                $db->where('order_status', '<', 2);
                break;
            case 3:
                $db->where('send_status', '=', 1);
                break;
            case 4:
                $db->where('send_status', '=', 2);
                break;
        }
        $list = $db->orderBy('id', 'desc')->paginate($limit);
        foreach ($list as $key => $vv) {
            $list[$key]['order_status_name'] = Prstatic::$orderStatus[$vv['order_status']];
            $list[$key]['send_status_name'] = Prstatic::$orderSendStatus[$vv['send_status']];
        }
        return $list;
    }

    /**
     * 获取信息
     * @param $id
     */
    public static function getInfoById($id, $store_id)
    {
        $info = self::where(['id' => $id, 'store_id' => $store_id])
            ->select(['id', 'order_sn', 'total_number', 'order_amount', 'order_name', 'order_mobile', 'goods_pay_amount',
                'order_province', 'order_city', 'order_area', 'order_address', 'express_company', 'freight', 'email', 'remark', 'created_at','tracking_number'])->first();
        if ($info) {
            return $info->toArray();
        }
        return [];
    }

    

    /**
     * 修改消息
     */
    public static function editInfo($data)
    {
        $info['order_name'] = $data['order_name'];
        $info['order_mobile'] = $data['order_mobile'];
        $info['order_province'] = $data['order_province'];
        $info['order_city'] = $data['order_city'];
        $info['order_area'] = $data['order_area'];
        $info['order_address'] = $data['order_address'];
        $info['tracking_number'] = $data['tracking_number'];
        $info['remark'] = $data['remark'];
        if ($data['id']) {
            return self::where(['id' => $data['id']])->update(array_filter($info));
        }
        return false;
    }

    /**
     * 推送库存同步数据到旺店通
     * @param int $rec_id
     * @param int $sync_stock
     * @param int $stock_change_count
     */
    public function syncStockToWdt($rec_id, $sync_stock, $stock_change_count)
    {
        $data = [
            [
                'rec_id' => $rec_id,
                'sync_stock' => $sync_stock,
                'stock_change_count' => $stock_change_count,
            ]
        ];

        $sid = config('services.wdt.sid');
        $appkey = config('services.wdt.appkey');
        $secret = config('services.wdt.secret');
        $url = config('services.wdt.url') . 'api_goods_stock_change_ack.php';

        $c = new \App\Console\Commands\WdtClient($sid, $appkey, $secret, $url);
        $c->putApiParam('stock_sync_list', json_encode($data, JSON_UNESCAPED_UNICODE));
        $result = $c->wdtOpenApi();

        \Log::info('实时同步库存到旺店通', ['data' => $data, 'result' => $result]);
        return $result;
    }
    /**
     * 推送库存同步数据到Redis队列
     * @param int $rec_id
     * @param int $sync_stock
     * @param int $stock_change_count
     */
//    public static function pushStockSyncToRedis($rec_id, $sync_stock, $stock_change_count)
//    {
//        $data = [
//            'rec_id' => $rec_id,
//            'sync_stock' => $sync_stock,
//            'stock_change_count' => $stock_change_count,
//        ];
//        Redis::rpush('stock_sync:inventory:push', json_encode($data, JSON_UNESCAPED_UNICODE));
//    }

    /**
     * @param $store_id
     * @param $data
     */
    public static function addInfoBySid($store_id, $data)
    {
        # 订单号
        $nowTime = time();
        $datett = date('Y-m', $nowTime) . "-01 00:00:01";
        $startTime = strtotime($datett);
        $endTime = $nowTime + 86400;
        $num = self::whereBetween('created_at', [$startTime, $endTime])->count();
        if ($num > 0) {
            $order_sn = self::where([])->orderBy('id', 'desc')->value('order_sn');
            $num = substr($order_sn, -4);
        }
        # 数据
        $info['store_id'] = $store_id;
        $info['order_sn'] = pdOrderSn($num + 1);
        $info['order_name'] = $data['order_name'];
        $info['order_mobile'] = $data['order_mobile'];
        $info['order_province'] = $data['order_province'];
        $info['order_city'] = $data['order_city'];
        $info['order_area'] = $data['order_area'];
        $info['order_address'] = $data['order_address'];
        $info['order_amount'] = $data['order_amount'];
        $info['goods_pay_amount'] = $data['goods_pay_amount'];
        $info['goods_amount'] = $data['goods_amount'];
        $info['total_number'] = $data['total_number'];
        $info['email'] = $data['email'];
        $info['express'] = '快递';
        $info['express_id'] = $data['express_id'];
        $info['express_company'] = $data['express_company'];
        $info['freight'] = $data['freight'];
        $info['order_status'] = $data['order_status'];
        $info['order_status_reason'] = $data['order_status_reason'];
        $info['send_status'] = 1;
        $info['remark'] = $data['remark'];
        $info['order_time'] = time();
        $info['created_at'] = time();
        $info['created_user'] = $data['username'];
        $info['store_product_batch'] = $data['store_product_batch'] ?? "";
        $order_id = self::insertGetId(array_filter($info));
//        var_dump(json_encode($data['goods_list']));die();
        if ($order_id) {
            if ($data['goods_list']) {
                // 添加变量用于存储组合商品主商品的ID
                $groupMainGoodsId = 0;
                foreach ($data['goods_list'] as $vv) {
                    $vv['store_product_batch'] = $data['store_product_batch'];
                    
                    // 处理商品库存扣减
                    $goods = Goods::find($vv['goods_id']);
                    if ($goods) {
                        if ($goods->is_group == 1 && !empty($goods->goods_group)) {
                            // 组合商品库存处理
                            $subGoodsIds = explode(',', $goods->goods_group);
                            foreach ($subGoodsIds as $subGoodsId) {
                                $subGoods = Goods::find($subGoodsId);
                                if ($subGoods) {
                                    // 扣减子商品库存
                                    $subGoods->decrement('goods_sale_num', $vv['goods_num']);
                                    $subGoods->decrement('goods_total_num', $vv['goods_num']);
//                                    // 写入库存同步队列
//                                    self::syncStockToWdt($subGoods->id, $subGoods->goods_sale_num, time());
                                }
                            }
                        }
                        
                        // 扣减主商品库存
                        $goods->decrement('goods_sale_num', $vv['goods_num']);
                        $goods->decrement('goods_total_num', $vv['goods_num']);
//                        // 写入库存同步队列
                        self::syncStockToWdt($goods->id, $goods->goods_sale_num, time());
                    }
                    
                    // 传递goods_group_pid参数
                    if ($vv['type'] == 2 && $vv['goods_pid'] == 0) {
                        // 组合商品主商品，获取插入记录的ID
                        $insertId = StoreOrderGoods::addInfoByOrderId($order_id, $store_id, $vv, $data['username']);
                        $groupMainGoodsId = $insertId;
                    } else if ($vv['type'] == 2 && $vv['goods_pid'] != 0) {
                        // 组合商品子商品，设置goods_group_pid
                        $vv['goods_group_pid'] = $groupMainGoodsId;
                        StoreOrderGoods::addInfoByOrderId($order_id, $store_id, $vv, $data['username']);
                    } else {
                        // 普通商品
                        StoreOrderGoods::addInfoByOrderId($order_id, $store_id, $vv, $data['username']);
                    }
                }
            }
            if ($data['goods_give_list']) {
                foreach ($data['goods_give_list'] as $vv) {
                    $vv['store_product_batch'] = $data['store_product_batch'];
                    StoreOrderGoods::addInfoByOrderId($order_id, $store_id, $vv, $data['username']);
                }
            }
            if ($data['ids']) {
                foreach ($data['ids'] as $id) {
                    StoreCart::where(['id' => $id, 'store_id' => $store_id])->delete();
                    StoreCart::where(['goods_pid' => $id, 'store_id' => $store_id])->delete();
                }
            }
            return $order_id;
        }
        return false;
    }
}